//
//  RuKuVC.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/9/22.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import UIKit
import SCLAlertView
import SVProgressHUD
protocol RuKuVCDelegate: class {
    func didSuccess()
}
class RuKuVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var addButton: UIButton!
    var rightBarItem: UIBarButtonItem!
    
    var items = [RuKu]()
    var material: MaterialDetail!
    var selectedColor: CodableColorOfMaterial!
    weak var delegate: RuKuVCDelegate?
    let helper = MaterialHelper()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.contentInset = UIEdgeInsetsMake(44, 0, 0, 0)
        tableView.delegate = self
        tableView.dataSource = self
        rightBarItem = UIBarButtonItem(title: "入库", style: .plain, target: self, action: #selector(rightBarButtonTapped(_:)))
        navigationItem.setRightBarButtonItems([rightBarItem], animated: true)
        addButton.addTarget(self, action: #selector(addButtonTapped(_:)), for: .touchUpInside)
        tableView.register(UINib(nibName: "RuKuCell", bundle: nil), forCellReuseIdentifier: "RuKuCell")
        
    }
    
    
    @objc func rightBarButtonTapped(_ button: UIBarButtonItem!) {
        guard items.count > 0 else {
            return
        }
        let input = Input(input: items)
        let encoder = JSONEncoder()
        let data = try! encoder.encode(input)
        SVProgressHUD.show()
        helper.input(with: data) { (error) in
            guard error == nil else {
                SVProgressHUD.showError(withStatus: error.debugDescription)
                return
            }
            SVProgressHUD.showSuccess(withStatus: "成功！")
            SVProgressHUD.dismiss(withDelay: 1.0)
            self.delegate?.didSuccess()
            self.navigationController?.popViewController(animated: true)
        }
        
        
    }
    
    @objc func addButtonTapped(_ button: UIButton!) {
        let appearence = SCLAlertView.SCLAppearance(showCloseButton: false, shouldAutoDismiss: true, hideWhenBackgroundViewIsTapped: false)
        
        let alertView = SCLAlertView(appearance: appearence)
        let nextAlertView = SCLAlertView(appearance: appearence)
        for color in material.color {
            alertView.addButton("\(color.no)-\(color.color)", action: {
                self.selectedColor = color
                let textField = nextAlertView.addTextField("请输入入库数量")
                textField.keyboardType = .numberPad
                nextAlertView.addButton("确定", action: {
                    guard let text = textField.text.nilIfEmpty else {
                        return
                    }
                    self.items.append(RuKu(materialId: self.material.id, colorId: color.id!, stock: Int(text)!, unit: self.material.unit))
                    self.tableView.beginUpdates()
                    self.tableView.insertRows(at: [IndexPath(row: self.items.count-1, section: 0)], with: .automatic)
                    self.tableView.endUpdates()
                })
                nextAlertView.showEdit("入库数量", subTitle: "", animationStyle: .rightToLeft)
            })
        }
        alertView.showInfo("选择入库颜色", subTitle: "", animationStyle: .topToBottom)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "RuKuCell") as! RuKuCell
        cell.stockLabel.text = "\(items[indexPath.row].stock)"
        cell.colorLabel.text = "\(selectedColor.no)-\(selectedColor.color)"
        cell.deleteButton.addTarget(self, action: #selector(deleteBtTapped(_:)), for: .touchUpInside)
        cell.selectionStyle = .none
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 66
    }
    @objc func deleteBtTapped(_ button: UIButton!) {
        let point = button.convert(CGPoint.zero, to: tableView)
        guard let indexPath = tableView.indexPathForRow(at: point) else {
            return
        }
        items.remove(at: indexPath.row)
        tableView.beginUpdates()
        tableView.deleteRows(at: [indexPath], with: .automatic)
        tableView.endUpdates()
    }
}
